<template>
	<view class="container flex_C">
		<FeNavbar title="买入" />
		<scroll-view class="scroll" scroll-y="true">
			<view class="wrap1">
				<view class="title">{{basicInfo.name}}</view>
				<view class="flex">
					<view class="flex_1">
						<view class="value">{{basicInfo.maxDrawdown}}%</view>
						<view class="label">最大回撤</view>
					</view>
					<view class="flex_1">
						<view class="flexV">
							<view class="value">{{basicInfo.leverageMultiplier}}X</view>
							<image class="icon" src="/static/mine/wenhao.png" @click="$refs.explain.show('杠杆说明')">
							</image>
						</view>
						<view class="label">杠杆</view>
					</view>
				</view>
			</view>
			<view class="wrap2">
				<view class="yield_wrap">
					<view class="day_wrap">
						<view class="flexV">
							<view class="sub">累计收益率</view>
							<image @click="$refs.explain.show('累计收益率说明')" class="wenhao" src="/static/mine/wenhao.png"
								mode=""></image>
						</view>
						<view class="date">
							{{returnRateIndex>-1?returnRate.strategy.returns[returnRateIndex].date:''}}
						</view>
						<view class="flexV">
							<view class="flex_1">
								<view class="earnings">
									<template v-if="returnRateIndex>-1">
										<template v-if="returnRate.strategy.returns[returnRateIndex].returnRate>0">
											+{{returnRate.strategy.returns[returnRateIndex].returnRate}}%
										</template>
										<template v-else>
											{{returnRate.strategy.returns[returnRateIndex].returnRate}}%
										</template>
									</template>
								</view>
								<view class="legend flexV">
									<view class="dian" style="--color:#FA8C4E"></view>
									<text class="label">累计收益率</text>
								</view>
							</view>
							<view class="flex_1">
								<view class="earnings">
									<template v-if="returnRateIndex>-1">
										<template v-if="returnRate.currencies[0].returns[returnRateIndex].returnRate>0">
											+{{returnRate.currencies[0].returns[returnRateIndex].returnRate}}%
										</template>
										<template v-else>
											{{returnRate.currencies[0].returns[returnRateIndex].returnRate}}%
										</template>
									</template>
								</view>
								<view class="legend flexV">
									<view class="dian" style="--color:#5FA7F0"></view>
									<text class="label">
										累计{{returnRateIndex>-1?returnRate.currencies[0].name:''}}趋势
									</text>
								</view>
							</view>
						</view>
					</view>
					<FeChart :option="yieldOption" v-on:chartClick="yieldChartClick" idName="yield_chart_02"
						height="390rpx">
					</FeChart>
				</view>
			</view>
			<view class="wrap3">
				<view class="from_item_wrap flexV">
					<view class="label">当前子账号</view>
					<!-- <picker class="child_account_wrap flexV"
						v-if="subAccountList.length"
						@change="bindPickerChange"
						range-key="subAccountName"
						:value="subAccountIndex"
						:range="subAccountList"
					>
						<view class="account van_ellipsis">{{subAccountList[subAccountIndex].subAccountName}}</view>
						<image class="icon" src="/static/mine/row-right.png" mode=""></image>
					</picker> -->
					<view class="child_account_wrap flexV" @click="selectSubAccount">
						<view class="account van_ellipsis" v-if="subAccountList.length">{{selectChildAccount}}</view>
						<view class="account van_ellipsis" v-if="!subAccountList.length&&subAccountLoad">暂无子账号</view>
						<image class="icon" src="/static/mine/row-right.png" mode=""></image>
					</view>
				</view>
				<view class="from_item_wrap">
					<view class="flexV">
						<view class="label">未使用资金</view>
						<view class="fund flexB">
							<text class="value">{{balance}}</text>
							<text class="unit"> USDT</text>
						</view>
					</view>
					<view class="flexV" style="margin-top: 28rpx;">
						<view class="slider_wrap flex_1">
							<u-slider v-model="ratioBalance" min="0" max="100" activeColor="#FFE269" />
							<view class="slider_value_wrap">
								<view class="slider_value" :style="{left:ratioBalance+'%'}">
									{{ratioBalance}}%
								</view>
							</view>
							<view class="slider_bottom flexV_sb">
								<text class="t">0</text>
								<text class="t">{{balance}}USDT</text>
							</view>
						</view>
						<input :disabled="!Number(balance)" :style="!Number(balance)?{backgroundColor:'#e9e9e9'}:{}"
							class="ratio_input" type="number" v-model="amount" @input="onAmountInput" />
					</view>
				</view>
				<view class="from_item_wrap flexV_sb cycle">
					<view class="label">购买周期</view>
					<view class="cycle_wrap flexV">
						<view class="item flexHV" :class="[index==cycleIndex?'on':'']" v-for="(item,index) in cycle"
							:key="index" @click="cycleIndex=index">
							{{item}}个月
						</view>
					</view>
				</view>
				<view class="from_item_wrap">
					<view class="flexV_sb">
						<view class="label">开仓保证金</view>
						<view class="label">{{earnestMoney}} USDT</view>
					</view>
					<view class="hint">
						<text class="t">预充值余额 {{prepaidBalance}}USDT</text>
						<text class="t" v-if="earnestMoney>prepaidBalance">，<text class="t2">余额不足</text></text>
					</view>

					<view class="brokerage_explain flexV">
						<view class="bro-wrap" @click="$refs.explain.show('开仓保证金')">
							<text class="t">开仓保证金</text>
							<image class="icon" src="/static/mine/wenhao.png"></image>
						</view>
					</view>
					<view class="brokerage_explain flexV">
						<view class="bro-wrap" @click="$refs.explain.show('预估服务费')">
							<text class="t">预估服务费</text>
							<image class="icon" src="/static/mine/wenhao.png"></image>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="btn_wrap flexV_sb">
			<view class="btn flexHV" @click="onBuy">买入</view>
			<view class="btn btn2 flexHV" @click="handleShowRecharge">充值</view>
		</view>

		<!-- 充值面板 -->
		<rechargePanel ref="refRechargePanel" />

		<Explain ref="explain" />

		<!-- 子账号选择 -->
		<u-picker :closeOnClickOverlay="true" :show="pickerShow" :defaultIndex="defaultIndex" keyName="subAccountName"
			:columns="childList" confirmColor="#FFE269" @cancel="pickerShow = false" @confirm="handlePickerConfirm">
		</u-picker>
	</view>
</template>

<script>
	import {
		basicInfoApi,
		returnRateApi,
		purchaseApi,
		buyApi
	} from '@/api/strategy.js'
	import {
		listApi,
		accountUnusedFunds
	} from '@/api/subAccount.js'
	import {
		balanceApi,
		calcDeposit
	} from '@/api/prepaid.js'
	import {
		debounce
	} from '@/util/index.js';
	import FeNavbar from '@/components/FeNavbar/FeNavbar.vue'
	import FeChart from '@/components/FeChart/index.vue'
	import Explain from '@/components/explain/explain.vue'
	import rechargePanel from "@/components/rechargePanel/rechargePanel.vue"
	export default {
		components: {
			FeNavbar,
			FeChart,
			rechargePanel,
			Explain
		},
		data() {
			return {
				id: 0,
				cycle: [],
				cycleIndex: 0,
				returnRate: {},
				returnRateIndex: -1,
				basicInfo: {},
				yieldOption: {},
				// 为使用资金
				balance: 0,
				ratioBalance: 0,
				subAccountList: [],
				subAccountIndex: 0,

				defaultIndex: [0],
				selectChildAccount: "", // 选择的子账号
				childList: [
					[]
				],
				subAccountId: null, // 当前选择的子账号id
				subAccountLoad: false,

				amount: 0,
				// 判断是否是手动更改金额
				manualChange: false,
				// 余额充值余额
				prepaidBalance: 0,
				// 保证金
				earnestMoney: 0,

				// 
				pickerShow: false,

				//定时器
				time: null,
				time2: null

			}
		},
		onLoad(o) {
			this.id = o.id;
			this.getBasicInfo();
			this.getReturnRate();
			this.getPurchase();
		},
		onShow() {
			this.getPrepaidBalance()
			this.getSubAccountList();
		},
		computed: {},
		watch: {
			ratioBalance: {
				handler(val) {
					if (this.manualChange) {
						this.manualChange = false;
						return
					}
					this.amount = this.balance * (val / 100)
					if (this.time) {
						this.time = setTimeout(() => {
							clearTimeout(this.time)
							this.time = null
						}, 500)
						return
					}
					this.amount = Math.floor(this.amount)
				}
			},
			amount: {
				handler: debounce(function(val) {
					console.log(val, '111')
					this.getCalcDeposit(val)
				}, 600)
			},
			subAccountId: {
				handler: function(newV) {
					newV && this.getUserAssets()
				}
			}
		},
		methods: {
			// 获取预充值余额
			async getPrepaidBalance() {
				const res = await balanceApi()
				console.log(res, '1======')
				if (res.code == 200) {
					this.prepaidBalance = parseFloat(res.data.balance)
				}
			},
			// 获取策略基础信息
			async getBasicInfo() {
				const res = await basicInfoApi(this.id)
				if (res.code === 200) {
					this.basicInfo = res.data
				}
			},
			// 获取购买基础信息
			async getPurchase() {
				const res = await purchaseApi(this.id);
				console.log(res)
				if (res.code === 200) {
					this.cycle = res.data.availablePeriods
				}
			},
			async getReturnRate() {
				const res = await returnRateApi(this.id)
				if (res.code === 200) {
					this.returnRate = res.data;
					try {
						const returns = res.data.strategy.returns.reverse();
						this.returnRateIndex = returns.length - 1
						const currenciesReturns = res.data.currencies[0].returns.reverse();
						const serverData1 = returns.map((item) => item.returnRate);
						const serverData2 = currenciesReturns.map((item) => item.returnRate);
						const max = Math.floor(Math.max(...[...serverData1, ...serverData2]));
						const min = Math.ceil(Math.min(...[...serverData1, ...serverData2]));
						this.yieldOption = {
							color: ['#FFE269', '#5FA7F0'],
							grid: {
								top: 6,
								left: 0,
								bottom: 0,
								right: uni.upx2px(32),
								containLabel: true
							},
							xAxis: {
								type: 'category',
								boundaryGap: false,
								data: returns.map(item => item.date.slice(5)),
								axisLine: {
									show: false
								},
								axisTick: {
									show: false
								},
								splitLine: {
									show: false
								},
								axisLabel: {
									interval: 1,
									showMaxLabel: true
								}
							},
							yAxis: {
								type: 'value',
								min: min - 2 - Math.abs(min * .2),
								max: max + max * .2 + 2,
								splitLine: {
									show: true
								}
							},
							series: [{
								data: serverData1,
								type: 'line',
								lineStyle: {
									width: 2
								},
							}, {
								data: serverData2,
								type: 'line',
								lineStyle: {
									width: 2
								},
							}]
						}
					} catch (e) {
						console.log(e, '错误')
						//TODO handle the exception
					}
				}
			},
			// 获取子账号
			async getSubAccountList() {
				const res = await listApi()
				this.subAccountLoad = true;
				if (res.code == 200) {
					const {
						subAccounts
					} = res.data;
					this.subAccountList = res.data.subAccounts
					if (subAccounts.length) {
						const currentSubAccountId = Number(uni.getStorageSync('currentSubAccountId'));
						const ids = subAccounts.map(item => item.subAccountId)
						this.childList = [res.data.subAccounts]
						let index = ids.indexOf(currentSubAccountId)
						index = index < 0 ? 0 : index
						this.defaultIndex = [
							[index]
						]
						this.subAccountId = ids[index]
						this.selectChildAccount = subAccounts[index].subAccountName
					}
				}
			},
			handlePickerConfirm(vals) {
				uni.showLoading({
					title: ""
				})
				this.selectChildAccount = vals.value[0].subAccountName;
				this.subAccountId = vals.value[0].subAccountId;
				this.pickerShow = false;
			},
			selectSubAccount() {
				if (!this.subAccountList.length) {
					uni.showModal({
						title: '温馨提示',
						content: '暂无子账号，请先创建子账号',
						confirmText: '去创建',
						confirmColor: '#FFE269',
						success(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/tabbar/mine/subAccount/index'
								})
							}
						}
					})
					return
				}
				this.pickerShow = true;
			},
			// 获取未使用资金
			async getUserAssets() {
				const res = await accountUnusedFunds(this.subAccountId);
				if (res.code == 200) {
					this.balance = res.data.unusedFunds
				}
			},
			// 计算保证金
			async getCalcDeposit(amount) {
				const res = await calcDeposit({
					amount
				})
				if (res.code == 200) {
					this.earnestMoney = res.data.deposit
				}
			},
			yieldChartClick(val) {
				this.returnRateIndex = val.xIndex;
				this.yieldOption = {
					...this.yieldOption,
					series: [{
						...this.yieldOption.series[0],
						markLine: {
							symbol: 'none',
							lineStyle: {
								color: '#FFE269',
								type: 'solid'
							},
							label: {
								show: false
							},
							data: [{
								xAxis: val.xIndex,
							}, {
								yAxis: this.yieldOption.series[0].data[val.xIndex],
							}, {
								yAxis: this.yieldOption.series[1].data[val.xIndex],
								lineStyle: {
									color: '#5FA7F0',
								}
							}],
							animationDuration: 500
						},
					}, {
						...this.yieldOption.series[1],
					}]
				}
				if (this.time2) {
					clearTimeout(this.time2)
				}
				this.time2 = setTimeout(() => {
					this.time2 = null
					this.yieldOption = {
						...this.yieldOption,
						series: [{
							...this.yieldOption.series[0],
							markLine: {
								data: []
							}
						}, {
							...this.yieldOption.series[1],
						}]
					}
				}, 3000)
			},
			bindPickerChange(e) {

			},
			onAmountInput(e) {
				let {
					value
				} = e.detail;
				value = value.replace('.', '');
				const val = Number(value);

				this.$nextTick(() => {
					this.amount = val > this.balance ? Math.floor(Number(this.balance)) : val;
					this.manualChange = true;

					if (parseFloat(this.balance) > 0) {
						this.ratioBalance = ((this.amount / this.balance) * 100).toFixed(1);
					} else {
						this.ratioBalance = 0;
					}
				})
			},
			async onBuy() {
				const {
					amount,
					earnestMoney,
					prepaidBalance,
					subAccountId
				} = this;
				if (!subAccountId) {
					uni.showToast({
						icon: 'none',
						title: '请选择子账户'
					});
					return
				}
				if (!amount) {
					uni.showToast({
						icon: 'none',
						title: '请输入购买资金'
					});
					return
				}
				if (earnestMoney > prepaidBalance) {
					uni.showToast({
						icon: 'none',
						title: '预充值余额不足'
					});
					return
				}

				const {
					riskInfo
				} = uni.getStorageSync('userInfo');
				const nowTime = Date.parse(new Date()) / 1000;
				if (nowTime > riskInfo.expirationDate) {
					uni.showModal({
						title: '温馨提示',
						content: '您风险评估已过期，请重新评估。',
						cancelText: '取消',
						confirmText: '去评估',
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/common/riskAnswer'
								})
							}
						}
					})
					return
				}
				uni.showLoading({
					mask: true
				})
				const res = await buyApi(this.id, {
					subAccountId,
					amount,
					period: this.cycle[this.cycleIndex]
				})
				if (res.code == 200) {
					uni.showToast({
						icon: 'success',
						title: '买入成功~'
					})
					uni.setStorageSync('currentSubAccountId', -1111)
					const time = setTimeout(() => {
						clearTimeout(time)
						uni.redirectTo({
							url: '/pages/tabbar/order/detail?id=' + res.data.orderId
						})
					}, 800)
				}
			},
			handleShowRecharge() {
				const {
					amount,
					earnestMoney,
					prepaidBalance
				} = this;
				const diff = earnestMoney - prepaidBalance;
				this.$refs.refRechargePanel.show(diff > 0 ? {
					gap_amount: diff
				} : {});
			},
		}
	}
</script>

<style scoped lang="scss">
	/deep/ uni-slider {
		margin: 8px 12px
	}

	/deep/ uni-slider .uni-slider-handle-wrapper {
		height: 4px
	}

	/deep/ .u-popup {
		position: fixed;
		z-index: 999;
	}

	/deep/ .u-popup__content {
		border-radius: 20rpx 20rpx 0 0;
	}

	.container {
		height: 100vh;
		background-color: #F5F7F8;

		.scroll {
			flex: 1;
			height: 0;
			padding-bottom: 1px;
		}

		.wrap1 {
			background-color: #fff;
			padding: 32rpx;

			.title {
				font-weight: 600;
				font-size: 40rpx;
				color: #26282B;
				margin-bottom: 24rpx;
			}

			.value {
				font-weight: bold;
				font-size: 36rpx;
				color: #26282B;
			}

			.label {
				font-weight: 400;
				font-size: 24rpx;
				color: #7B828A;
				margin-top: 4rpx;
			}

			.icon {
				width: 32rpx;
				height: 32rpx;
				margin-left: 12rpx;
			}
		}

		.wrap2 {
			background-color: #fff;
			margin-top: 24rpx;
			padding: 32rpx;

			.tab_wrap {
				.tab_item {
					width: 214rpx;
					height: 56rpx;
					background: #EEF1F6;
					border-radius: 8rpx;
					font-weight: 400;
					font-size: 26rpx;
					color: #7B828A;
					transition: all .3s;

					&.on {
						background-color: #FFE269;
						color: #26282B;
					}
				}
			}

			.earnings_wrap {
				margin-top: 32rpx;
			}

			.day_wrap {
				margin-bottom: 24rpx;

				.sub {
					font-weight: 600;
					font-size: 28rpx;
					color: #26282B;
				}

				.date {
					font-weight: 400;
					font-size: 24rpx;
					color: #A6ACB4;
					margin-top: 4rpx;
				}

				.earnings {
					font-weight: bold;
					font-size: 44rpx;
					color: #06B070;
					margin-top: 20rpx;
				}

				.wenhao {
					width: 32rpx;
					height: 32rpx;
					margin-left: 12rpx;
				}

				.legend {
					margin-top: 8rpx;

					.dian {
						width: 12rpx;
						height: 12rpx;
						border-radius: 50%;
						background-color: var(--color);
					}

					.label {
						font-weight: 400;
						font-size: 24rpx;
						color: #7B828A;
						margin-left: 8rpx;
					}
				}
			}

		}

		.wrap3 {
			background-color: #fff;
			padding: 0 32rpx;
			margin-top: 24rpx;
			margin-bottom: 240rpx;

			.from_item_wrap {
				padding: 34rpx 0;
				border-bottom: 1px solid #DBE0E6;

				&.cycle {
					padding: 25rpx 0;
				}

				&:last-child {
					border: none;
				}

				.label {
					font-weight: 400;
					font-size: 28rpx;
					color: #26282B;
				}

				.child_account_wrap {
					margin-left: auto;

					.account {
						max-width: 380rpx;
						font-weight: 400;
						font-size: 30rpx;
						color: #7B828A;
					}

					.icon {
						width: 24rpx;
						height: 24rpx;
						margin-left: 20rpx;
					}
				}

				.fund {
					color: #26282B;
					margin-left: 16rpx;
					transform: translateY(-2rpx);

					.value {
						font-weight: bold;
						font-size: 44rpx;
					}

					.unit {
						font-weight: bold;
						font-size: 30rpx;
						margin-left: 4rpx;
					}
				}

				.cycle_wrap {
					.item {
						width: 120rpx;
						height: 58rpx;
						background: #EEF1F6;
						border-radius: 8rpx;
						font-weight: 400;
						font-size: 24rpx;
						color: #7B828A;
						margin-left: 28rpx;
						transition: all .3s;

						&.on {
							background: #FFE269;
							color: #26282B;
						}
					}
				}

				.hint {
					margin-top: 4rpx;
					text-align: right;

					.t {
						font-weight: 400;
						font-size: 22rpx;
						color: #A6ACB4;

						.t2 {
							color: #F04848;
						}
					}
				}

				.ratio_input {
					width: 142rpx;
					height: 60rpx;
					background: #FFFFFF;
					border-radius: 12rpx;
					border: 2rpx solid #DBE0E6;
					text-align: center;
					font-weight: 400;
					font-size: 28rpx;
					color: #26282B;
				}

				.slider_bottom {
					margin-top: -10rpx;
					padding: 0 12px;

					.t {
						font-weight: 400;
						font-size: 24rpx;
						color: #7B828A;
					}
				}

				.slider_wrap {
					position: relative;

					.slider_value_wrap {
						position: absolute;
						top: -20rpx;
						right: 12px;
						left: 12px;
					}

					.slider_value {
						position: absolute;
						font-weight: 400;
						font-size: 24rpx;
						color: #7B828A;
						transform: translateX(-50%);
					}
				}
			}
		}

		.brokerage_explain {
			height: 74rpx;
			// padding: 0 32rpx;
			display: flex;
			align-items: center;
			justify-content: flex-end;

			.bro-wrap {
				display: flex;
				align-items: center;
			}

			.t {
				font-weight: 400;
				font-size: 24rpx;
				color: #A6ACB4;
				margin-left: auto;
			}

			.icon {
				width: 28rpx;
				height: 28rpx;
				margin-left: 8rpx;
			}
		}

		.hr {
			height: 1rpx;
		}

		.btn_wrap {
			padding: 0 32rpx;
			height: 116rpx;
			background-color: #fff;
			border-top: 1px solid #DBE0E6;

			.btn {
				width: 322rpx;
				height: 88rpx;
				background: #63D0A8;
				border-radius: 12rpx;
				font-weight: 600;
				font-size: 30rpx;
				color: #FFFFFF;

				&.btn2 {
					background-color: #FFE269;
					color: #26282B;
				}
			}
		}
	}
</style>